package com.currency.mall.ui.my.recharge;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.adapter.RechargeStatusAdapter;
import com.currency.mall.entity.RechargeBean;
import com.currency.mall.entity.RechargeRecordBean;
import com.currency.mall.entity.RechargeStatus;
import com.currency.mall.netWork.NetWork;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.commonbase.util.ToastUitl;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/24.
 */

public class RechargeRecordFragment extends BaseFragment {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    @BindView(R.id.rv_recharge_statu)
    RecyclerView rvRechargeStatu;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ll_not_data)
    RelativeLayout llNotData;
    private RechargeStatusAdapter mRechargeStatusAdapter;
    private int mCurrentPage;
    private int position;//当前位置
    private String status;//资金状态
    private List<RechargeStatus> rechargeStatusList = new ArrayList<>();
    private String price;
    private int type;// 0银行卡  1 支付宝


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_recharge_status, container, false);
        unbinder = ButterKnife.bind(this, mView);
        position = FragmentPagerItem.getPosition(getArguments());
        init();
        return mView;
    }

    private void init() {
        setStatus();
        rvRechargeStatu.setLayoutManager(new LinearLayoutManager(getContext()));
        rvRechargeStatu.setNestedScrollingEnabled(false);
//        refreshLayout.setEnableLoadMore(false);
        mRechargeStatusAdapter = new RechargeStatusAdapter(null, getContext());
        rvRechargeStatu.setAdapter(mRechargeStatusAdapter);
        mRechargeStatusAdapter.openLoadAnimation();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    setStatus();
                    rechargeStatusList.clear();
                    mCurrentPage = 1;
                    getRechargeData(mCurrentPage);
                }
            }
        });
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                                       int oldScrollY) {
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    onLoadMoreRequested();
                }
            }
        });

        mRechargeStatusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int index) {
                Intent intent = null;
                if (rechargeStatusList != null || rechargeStatusList.size() > 0) {


                    RechargeStatus rechargeStatus = rechargeStatusList.get(index);

                    intent = new Intent(getContext(), WaitConfirmActivity.class);
                    intent.putExtra("rechargeStatus", rechargeStatus);
                    if (position == 0) {
                        if ("PAY_WAIT".equals(rechargeStatus.getStatus())) {
                            price = rechargeStatus.getRecharSum();
                            recharge(rechargeStatus);
                        } else {
                            intent.putExtra("type", 0);
                            startActivity(intent);
                        }

                    } else if (position == 1) {
                        intent.putExtra("type", 1);
                        startActivity(intent);
                    } else if (position == 2) {
                        intent.putExtra("type", 2);
                        startActivity(intent);
                    }

                }


            }
        });
        getRechargeData(1);
    }

    /**
     * 充值记录
     *
     * @param page
     */
    public void getRechargeData(int page) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", status);
        hashMap.put("pageNum", page);
        hashMap.put("pageSize", 20);
        NetWork.getOderApi().rechargeOrder(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RechargeRecordBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        finishRefresh();
                    }

                    @Override
                    public void onNext(RechargeRecordBean rechargeRecordBean) {
                        finishRefresh();
                        if (rechargeRecordBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            setData(rechargeRecordBean.getPageList());
                        } else {
                            ToastUitl.show(rechargeRecordBean.getMsg(), 200);
                        }

                    }
                });
    }

    public void recharge(final RechargeStatus rechargeStatus) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", rechargeStatus.getId());
        showLoading();
        NetWork.getOderApi().rechargeInfo(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RechargeBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }

                    @Override
                    public void onNext(RechargeBean rechargeBean) {
                        hideLoading();
                        if (rechargeBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            if ("ALIPAY".equals(rechargeStatus.getType())) {
                                type = 1;
                            } else {
                                type = 0;
                            }
                            toRechargeIntent(rechargeBean, type);
                        } else {
                            ToastUitl.show(rechargeBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void toRechargeIntent(RechargeBean rechargeBean, int type) {
        Intent intent = new Intent(getContext(), RechargeDetailsActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("timeOut", rechargeBean.getTimeOut());
        intent.putExtra("bankInfo", rechargeBean.getBankInfo());
        intent.putExtra("rechargeInfo", rechargeBean.getRecharge());
        intent.putExtra("alipayInfo", rechargeBean.getAlipayInfo());
        intent.putExtra("price", price);
        startActivity(intent);
    }

    public void onLoadMoreRequested() {
        mCurrentPage++;
        getRechargeData(mCurrentPage);
    }


    private void setStatus() {
        if (position == 0) {
            status = "PAY_OPERATION";
        } else if (position == 1) {
            status = "PAY_SUCCESS";
        } else if (position == 2) {
            status = "PAY_CANCEL";
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void setData(RechargeRecordBean.RechargeRecordInfo rechargeRecordInfo) {
        rechargeStatusList = rechargeRecordInfo.getList();
        if(rechargeStatusList.size() == 0){
            llNotData.setVisibility(View.VISIBLE);
        }else{
            llNotData.setVisibility(View.GONE);
        }
        mRechargeStatusAdapter.setNewData(rechargeStatusList);

    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();
    }

    public int position() {
        return position;
    }
}
